package com.itheima.task;

import com.itheima.dao.OrderDao;
import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class OrderTimeoutTask {
    // 注入的dao和service
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisUtil redisUtil;  // 可能未被正确注入导致null

    @Scheduled(cron = "*/10 * * * * ?")
    public void handleTimeoutOrders() {
        System.out.println("=== 开始扫描超时未支付订单 ===" + new Date());

        // 1. 首先检查RedisUtil是否为null（关键修复点）
        if (redisUtil == null) {
            System.err.println("RedisUtil未被正确注入，无法执行超时订单扫描");
            return;
        }

        String key = "order:timeout:zset";
        long currentTime = System.currentTimeMillis();

        try {
            // 2. 执行Redis查询，确保处理可能的null返回
            Set<Object> timeoutOrderIds = redisUtil.zRangeByScore(key, 0, currentTime);

            // 3. 处理Redis返回结果为null的情况
            if (timeoutOrderIds == null) {
                System.out.println("Redis查询超时订单返回null，本次扫描结束");
                return;
            }

            if (!timeoutOrderIds.isEmpty()) {
                for (Object orderIdObj : timeoutOrderIds) {
                    // 4. 检查订单ID对象是否为null
                    if (orderIdObj == null) {
                        System.out.println("发现空的订单ID，跳过处理");
                        continue;
                    }

                    try {
                        Integer orderId = Integer.parseInt(orderIdObj.toString());
                        Order order = orderDao.findOrderById(orderId);

                        if (order == null) {
                            System.out.println("订单" + orderId + "不存在，从Redis中移除");
                            redisUtil.zRemove(key, orderIdObj);
                            continue;
                        }

                        Integer productId = order.getProductId();
                        // 5. 检查productId是否为null
                        if (productId == null) {
                            System.out.println("订单" + orderId + "的商品ID为空，无法处理");
                            redisUtil.zRemove(key, orderIdObj);
                            continue;
                        }

                        Product product = productService.findProductById(productId);
                        if (product == null) {
                            System.out.println("订单" + orderId + "对应的商品" + productId + "不存在");
                            redisUtil.zRemove(key, orderIdObj);
                            continue;
                        }

                        // 处理订单超时逻辑
                        orderDao.updateStatus3(orderId);
                        productService.uploadProductF1(productId);
                        redisUtil.zRemove(key, orderIdObj);
                        System.out.println("订单" + orderId + "已超时自动关闭，商品库存已恢复");

                    } catch (NumberFormatException e) {
                        System.out.println("订单ID格式错误，无法转换为数字：" + orderIdObj);
                        redisUtil.zRemove(key, orderIdObj);
                    } catch (Exception e) {
                        System.out.println("处理订单" + orderIdObj + "时发生异常：" + e.getMessage());
                    }
                }
            }
            System.out.println("=== 超时订单扫描处理完成，共处理" + timeoutOrderIds.size() + "个订单 ===" + new Date());

        } catch (Exception e) {
            // 捕获Redis操作可能发生的异常
            System.err.println("执行超时订单扫描时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
